package com.gac.basedownload;

import android.os.Environment;
import android.util.Log;

import com.gac.basedownload.inner.DBUtils;
import com.gac.basedownload.model.DownloadRecord;
import com.gac.basedownload.model.FileRecord;
import com.gac.basedownload.model.RemoteFile;
import com.gac.basedownload.model.RemoteFileUtil;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GacDownload {


    //
    private static GacDownload mDownload;
    private ExecutorService threadPool;

    private FileRecord fileRecord;

    private boolean isFinish = false;

    private boolean isSupportMultilThread = false;
    private GacDownload(Builder builder){
        fileRecord = DBUtils.getFileRecordByUrl(builder.mUrl);
        if(fileRecord != null ){
            if(fileRecord.getDownloadLen() == fileRecord.getFileLen()){
                isFinish = true;
                //下载完成
            }else{
                isFinish = false;
                //下载没有完成 清除记录 重新下载 暂时这么处理
                DBUtils.removeFileRecord(fileRecord);
            }
        }


        threadPool = Executors.newFixedThreadPool(3);

        fileRecord = new FileRecord();
        fileRecord.setFileName(builder.mFileName);
        fileRecord.setFileId(UUID.randomUUID().toString());
        fileRecord.setDownloadLen(0);
        fileRecord.setSavePath(builder.mFilePath);
        fileRecord.setUrl(builder.mUrl);

        //获取文件长度 和是否支持多线程下载
        RemoteFile remoteFile = RemoteFileUtil.getRemoteFileLength(builder.mUrl);
        isSupportMultilThread = remoteFile.isSupportRange();
        if(isSupportMultilThread){
            fileRecord.setThreadCount(3);
        }else{
            fileRecord.setThreadCount(1);
        }
        fileRecord.setFileLen(remoteFile.getLength());
        fileRecord.setDownloadLen(0L);
        DBUtils.insertFileRecord(fileRecord);


    }

    private void childThreadFinishDownload(long total, DownloadRecord record) {


        DBUtils.updateDownloadRecord(record);
        long downloadedLen = DBUtils.getDownloadedLen(fileRecord.getFileId());
        Log.e("gacmy","一个线程下载完成了...."+total+" downloadLen:"+downloadedLen+" fileLen:"+fileRecord.getFileLen()+
                " recordLen:"+record.getDownloadLen());

        if(downloadedLen == fileRecord.getFileLen()){
            //
            fileRecord.setDownloadLen(downloadedLen);
            DBUtils.updateFileRecord(fileRecord);
            Log.e("gacmy","下载完成....");
        }
    }

    public void startDownload(){
        if(isFinish){
            Log.e("gacmy","下载完成 不需要下载");
            return;
        }

        if(isSupportMultilThread){//支持多线程
            //分段大小
            final long div = fileRecord.getFileLen() / 3;
            long lastIndex = 0;

            for(int i = 0; i < 3; i++){
                DownloadTask downloadThread;
                DownloadRecord record;
                if (i != 2) {
                    Log.e("gacmy","最后一个线程启动");

                    //0 33   34 68  69 99
                    record = new DownloadRecord();
                    record.setStartIndex(lastIndex);
                    record.setEndIndex(div*(i+1));
                    record.setFileId(fileRecord.getFileId());
                    record.setThreadId(UUID.randomUUID().toString());

                    downloadThread = new DownloadTask(fileRecord, record, new DownloadTask.ThreadDownloadListener() {
                        @Override
                        public void onDownload(long currentDownloadSize, DownloadRecord record) {

                        }

                        @Override
                        public void onFinish(long total, DownloadRecord record) {
                            childThreadFinishDownload(total,record);
                        }

                        @Override
                        public void onPause() {

                        }

                        @Override
                        public void onFail() {

                        }
                    });

                } else {
                    record = new DownloadRecord();
                    record.setStartIndex(lastIndex);
                    record.setEndIndex(fileRecord.getFileLen()-1);
                    record.setFileId(fileRecord.getFileId());
                    record.setThreadId(UUID.randomUUID().toString());
                    downloadThread = new DownloadTask(fileRecord, record, new DownloadTask.ThreadDownloadListener() {
                        @Override
                        public void onDownload(long currentDownloadSize, DownloadRecord record) {

                        }

                        @Override
                        public void onFinish(long total, DownloadRecord record) {
                            childThreadFinishDownload(total,record);
                        }

                        @Override
                        public void onPause() {

                        }

                        @Override
                        public void onFail() {

                        }
                    });

                }
                DBUtils.insertDownloadRecord(record);
                Log.e("gacmy","一个线程启动:"+DBUtils.getAllDownloadCount());
                threadPool.execute(downloadThread);
                lastIndex = div * (i + 1) + 1;

            }
        }else{//不支持多线程
            //
            DownloadTask downloadThread;
            DownloadRecord record;
            //0 33   34 68  69 99
            record = new DownloadRecord();
            record.setStartIndex(0);
            record.setEndIndex(fileRecord.getFileLen()-1);
            record.setFileId(record.getFileId());
            record.setThreadId(UUID.randomUUID().toString());
            downloadThread = new DownloadTask(fileRecord, record, new DownloadTask.ThreadDownloadListener() {
                @Override
                public void onDownload(long currentDownloadSize, DownloadRecord record) {

                }

                @Override
                public void onFinish(long total, DownloadRecord record) {
                    Log.e("gacmy","单线程下载...");
                    childThreadFinishDownload(total,record);
                }

                @Override
                public void onPause() {

                }

                @Override
                public void onFail() {

                }
            });


            DBUtils.insertDownloadRecord(record);
            threadPool.execute(downloadThread);

        }


    }
    public static class Builder{
        private String mUrl;
        private String mFileName;
        private String mFilePath;

        public Builder url(String url){
            this.mUrl = url;
            return this;
        }

//        public Builder fileName(String fileName){
//
//        }



        public GacDownload build() {
            String fileType = mUrl.substring(mUrl.lastIndexOf("."));

            mFileName = (UUID.randomUUID().toString())+fileType;
            mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+mFileName;
            File path = new File(mFilePath);
            if(!path.exists()){
                try {
                    path.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return new GacDownload(this);
        }
    }



}
